<?php

namespace addons\helper\controller\wxapp\general;

use app\admin\model\StoreShop;
use app\admin\model\Admin;
use addons\helper\controller\wxapp\Base;
use addons\helper\library\Alisms;
use addons\helper\library\Weapp;
use app\admin\model\helper\User;
use fast\Random;
use think\Session;
use think\Validate;

class Profile extends Base
{
    protected $searchFields = 'id';
    protected $noNeedRight = '*';
    protected $config = [
        'model'             => '日志',
        'limit'             => 10,
        'defaultSort'       => 'id',
        'defaultOrder'      => 'desc',
        'tabField'          => '',
        'search'            => true,
        'filter'            => true,
        'multi'             => true,
        'sort'              => true,
        'searchPlaceholder' => '输入ID搜索',
        'field' => [
            'admin_id'   => ['管理员ID', 'number', false,  false, '', true, false, false],
            'username'   => ['管理员名', 'text', false,  false, '', true, false, false],
            'url'        => ['操作页面', 'text', false,  false, '', true, true, true],
            'title'      => ['日志标题', 'text', true,  true, 'like', true, true, true],
            'content'    => ['内容', 'text', false,  false, '', true, false, false],
            'ip'         => ['IP地址', 'text', false,  true, '=', true, false, false],
            'useragent'  => ['内容', 'text', false,  false, '', true, false, false],
            'createtime' => ['操作时间', 'datetime', true, true, 'RANGE', true, false, false],
        ],
        'auth' => [
            'multi' => [
                'del'  => [
                    'name'        => '删除',
                    'btnColor'    => 'danger',
                    'icon'        => 'fa-trash',
                    'url'         => 'general.attachment/del'
                ],
            ]
        ]
    ];
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AdminLog;
        $this->config['field'] = $this->formatField();
        $this->config['pk'] = $this->model->getPk() ? $this->model->getPk() : 'id';
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isPost()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->where($where)
                ->where('admin_id', $this->userId)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->where($where)
                ->where('admin_id', $this->userId)
                ->order($sort, $order)
                ->limit($offset, $limit ? $limit : $this->config['limit'])
                ->select();

            $result = array("total" => $total, "rows" => $list);

            $data = [
                'tabList'  => null,
                'dataList' => $result,
                'config'   => $this->config
            ];
            $this->success('ok', $data);
        }
        $this->success('ok', $this->getUserInfo());
    }
    /**
     * 更新个人信息
     */
    public function update()
    {
        if ($this->request->get('action') === 'sendCaptchaSms') {
            $this->sendCaptchaSms();
        }
        if ($this->request->post('wechat') === 'bind') {
            $this->bindWechat();
        }
        if ($this->request->post('wechat') === 'unbind') {
            $this->unbindWechat();
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (isset($params['email']) && !Validate::is($params['email'], "email")) {
                $this->error(__("Please input correct email"));
            }
            if (isset($params['password']) && strlen($params['password'])) {
                if (!Validate::is($params['password'], "/^[\S]{6,16}$/")) {
                    $this->error(__("Please input correct password"));
                }
                $params['salt'] = Random::alnum();
                $params['password'] = md5(md5($params['password']) . $params['salt']);
            }else{
                unset($params['password']);
            }
            $exist = isset($params['email']) ? Admin::where('email', $params['email'])->where('id', '<>', $this->userId)->find() : false;
            if ($exist) {
                $this->error(__("Email already exists"));
            }
            if (isset($params['mobile'])) {
                $mobile = $params['mobile'];
                $captcha = (string) $params['captcha'];
                $config = get_addon_config('helper');
                $config['SmsCodeExpireSec'] = (int) $config['SmsCodeExpireSec'] ?: 180;
                if (!(int) $config['IsMobileBind']) {
                    $this->error('已禁止手机号码绑定');
                }
                // 手机号码检查
                $check  = '/^(1(([345789][0-9])|(47)))\d{8}$/';
                if (!preg_match($check, $mobile)) {
                    $this->error('手机号码格式不正确');
                }
                // 验证码检查
                $code    = Session::get('captcha_sms.code');
                $time    = Session::get('captcha_sms.time');
                if ($time + $config['SmsCodeExpireSec'] < time()) {
                    $this->error('验证码已过期，请重新发送。');
                }
                if ($mobile !== Session::get('captcha_sms.mobile')) {
                    $this->error('验证码不正确');
                }
                
                if ($captcha !== $code) {
                    $this->error('验证码不正确');
                }
                // 账号检查
                $admin  = Admin::get(['mobile' => $mobile]);
                if ($admin) {
                    $this->error($mobile . '已绑定其它账号');
                }
            }
            if ($params) {
                $admin = Admin::get($this->userId);
                $admin->allowField(['email', 'nickname', 'password', 'salt', 'avatar', 'mobile'])->save($params);
                $this->success('修改成功');
            }
            $this->error();
        }
    }
    public function getKpi()
    {

        $data=(new Admin())->getAgentKpi($this->userId);
       $this->success('ok',  $data);


    }

    public function getDayKpi()
    {
        $value=$this->request->param('value');
        $time=$this->request->param('time');
        //1-今天,2-昨天,3-一周
        $data=(new Admin())->getDayKpi($this->userId,$value,$time);
        $this->success('ok',  $data);
    }





    public function getshop()
    {


        if ($this->userId != get_addon_config('douyin')['super_id']) {
            $child = (new Admin())->getAgentChild($this->userId, 'shop_id');

            if ($child) {
                $list=(new StoreShop())->where('id','in',$child)->field('id as value,name as label')->select();
            } else {
                $shop_id = (new Admin())->where('id', $this->userId)->value('shop_id');
                if ($shop_id) {
                    $list=(new StoreShop())->where('id',$shop_id)->field('id as value,name as label')->select();
                }
            }
        }else {
            $list=(new StoreShop())->field('id as value,name as label')->select();
        }
        $this->success('ok', $list);



    }






    protected function sendCaptchaSms()
    {
        // 手机号码检查
        $mobile = $this->request->get('mobile');
        $check  = '/^(1(([345789][0-9])|(47)))\d{8}$/';
        if (!preg_match($check, $mobile)) {
            $this->error('手机号码格式不正确');
        }
        // 账号检查
        $admin  = Admin::get(['mobile' => $mobile]);
        if ($admin) {
            $this->error($mobile . '已绑定其它账号');
        }
        // 两次发送间隔检查 默认60秒
        if (Session::has('captcha_sms.time')) {
            if (time() < Session::get('captcha_sms.time') + 60) {
                $interval = Session::get('captcha_sms.time') + 60 - time();
                $this->error('请在' . $interval  . '秒后再发送');
            }
        }
        // 生成6位数字验证码
        $code   = rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
        // 记录session
        Session::set(
            'captcha_sms',
            [
                'mobile'      => $mobile,
                'code'        => $code,
                'time'        => time(),
            ]
        );
        // 模拟发送成功
        // $this->success('发送成功', $code);
        
        // 发送短信
        $config = get_addon_config('helper');
        $accessKeyId     = $config['AliSmsAccessKeyId'];
        $accessKeySecret = $config['AliSmsAccessKeySecret'];
        $signName        = $config['AliSmsSignName'];
        $TemplateCode    = $config['AliSmsTemplateCode'];
        $TemplateParam   = '{"code":"' . $code . '"}';
        $ext             = [];
        $sms = Alisms::sendSms($accessKeyId, $accessKeySecret, $mobile, $signName, $TemplateCode, $TemplateParam);
        $sms = json_decode($sms, true);
        if ($sms['Code'] === 'OK') {
            $this->success('发送成功');
        }
        $this->error('发送失败', $sms);
    }
    protected function bindWechat()
    {
        $config = get_addon_config('helper');
        if (!in_array('wechat', explode(',', $config['LoginType']))) {
            $this->error('已禁止微信登录');
        }
        $code     = $this->request->post('code');
        $userInfo = $this->request->post('userInfo/a');
        if (!$code || !$userInfo) {
            $this->error('缺少必要参数');
        }
        $session = Weapp::code2Session($config['AppID'], $config['AppSecret'], $code);
        if (isset($session['errcode']) && $session['errcode']) {
            $this->error($session['errmsg'],$session['code']);
        }
        $sessionKey = $session['session_key'];
        $decryptData = Weapp::decryptData($config['AppID'], $userInfo['encryptedData'], $userInfo['iv'], $sessionKey);
        if ($decryptData['code'] < 0) {
            $this->error($decryptData['msg'],$decryptData['code']);
        }
        $exist = User::get(['wxopenid' => $decryptData['data']['openId']]);
        if ($exist) {
            $this->error('绑定失败，此微信账号已与其它账号绑定。');
        }
        $data = [
            'wxopenid'    => $decryptData['data']['openId'],
            'wxnickname'  => $decryptData['data']['nickName'],
            'wxgender'    => $decryptData['data']['gender'],
            'wxcity'      => $decryptData['data']['city'],
            'wxprovince'  => $decryptData['data']['province'],
            'wxcountry'   => $decryptData['data']['country'],
            'wxavatarurl' => $decryptData['data']['avatarUrl'],
            'wxunionid'   => isset($decryptData['data']['unionId']) ? $decryptData['data']['unionId'] : '',
        ];
        $user = User::get(['user_id' => $this->userId]);
        $user->save($data);
        $this->success('绑定成功');
    }
    protected function unbindWechat()
    {
        $user = User::where('user_id',$this->userId)->setField('wxopenid', '');
        if($user){
            $this->success('解绑成功');
        }
        $this->error('解绑失败');
    }
}
